package com.surfilter.risk.service.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.surfilter.risk.constant.ConstantStr;
import com.surfilter.risk.dto.*;
import com.surfilter.risk.entity.Page;
import com.surfilter.risk.entity.PunishTypeNum;
import com.surfilter.risk.entity.TopSearchCondition;
import com.surfilter.risk.enums.CodeStateEnum;
import com.surfilter.risk.exception.ConditionSPageException;
import com.surfilter.risk.exception.ConditionTimeException;
import com.surfilter.risk.exception.ConditionTypeException;
import com.surfilter.risk.exception.QueryException;
import com.surfilter.risk.mapper.BusinessRiskListMenuMapper;
import com.surfilter.risk.mapper.BusinessRiskListTopTenMapper;
import com.surfilter.risk.mapper.BusinessRiskListViewMapper;
import com.surfilter.risk.mapper.RiskListGeneralMapper;
import com.surfilter.risk.service.RiskListGeneralService;
import com.surfilter.risk.utils.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * RiskListGeneralServiceImpl
 * Dis:
 * Created by grom on 2017/5/12.
 */
@Service("riskListGeneralService")
public class RiskListGeneralServiceImpl implements RiskListGeneralService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RiskListGeneralMapper riskListGeneralMapper;

    @Autowired
    BusinessRiskListTopTenMapper businessRiskListTopTenMapper;

    @Autowired
    BusinessRiskListMenuMapper businessRiskListMenuMapper;

    @Autowired
    BusinessRiskListViewMapper businessRiskListViewMapper;

    /**
     * 企业风险榜单-总体概况数据
     *
     * @return
     */
    @Transactional
    @Override
    public String businessRiskListGeneral() {
        //result
        Map<String, Object> result = Maps.newHashMap();
        //data
        RiskListGeneral data;
        try {
            data = getRiskListGeneralInfo();
            data.setPunishregion(getPunishregion());
            data.setPunishtype(getPunishtypeProportion());
            data.setPunishstra(getPunishstra());
            data.setPunishcomp(getPunishcomp());
            data.setPunishdist(getPunishdist());
            data.setPunishlisted(getPunishlisted());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result.put(ConstantStr.CODE, CodeStateEnum.FAIL);
            result.put(ConstantStr.MSG, e.getMessage());
            //所有的编译时异常，转化为运行时异常（运行时异常，spring可以做rollback的操作）
            throw new QueryException("Query inner error : " + e.getMessage());
        }
        result.put(ConstantStr.DATA, data);
        result.put(ConstantStr.PUBLIC_OPTION_COUNT, "");
        return new Gson().toJson(result);
    }

    //总体概况
    public RiskListGeneral getRiskListGeneralInfo() {
        return riskListGeneralMapper.selectRiskListGeneral();
    }

    //地理区域处罚统计
    public List<GeneralData> getPunishregion() {
        return riskListGeneralMapper.selectPunishregion();
    }

    //全国行政处罚类型占比
    public List<GeneralData> getPunishtypeProportion() {
        List<GeneralData> result = Lists.newArrayList();
        PunishTypeNum punishTypeNum = riskListGeneralMapper.selectPunishType();
        GeneralData warningPunishProportion = new GeneralData("申诫罚",punishTypeNum.getWarningPunishNum());
        GeneralData estatePunishProportion = new GeneralData("财产罚",punishTypeNum.getEstatePunishNum());
        GeneralData behavioralPunishProportion = new GeneralData("行为罚",punishTypeNum.getBehavioralPunishNum());
        GeneralData personPunishProportion = new GeneralData("人身罚",punishTypeNum.getPersonPunishNum());
        result.add(warningPunishProportion);
        result.add(estatePunishProportion);
        result.add(behavioralPunishProportion);
        result.add(personPunishProportion);
        return result;
    }

    //全国行政单位处罚top10
    public List<GeneralData> getPunishstra() {
        return riskListGeneralMapper.selectPunishstra();
    }

    //全国企业处罚综合top10
    public List<GeneralData> getPunishcomp() {
        return riskListGeneralMapper.selectPunishcomp();
    }

    //全国行业分布处罚top10
    public List<GeneralData> getPunishdist() {
        return riskListGeneralMapper.selectPunishdist();
    }

    //上市公司处罚综合top10
    public List<GeneralData> getPunishlisted() {
        return riskListGeneralMapper.selectPunishlisted();
    }


    /**
     * 企业风险榜单-地区、行业、行政 top10
     *
     * @param spage 当前页面（1 地理区域榜  2 行业分类榜  3 行政单位榜）
     * @param type  排序条件（1 按处罚金额降序排列  2 按处罚次数降序排列）
     * @param year  年榜
     * @param month 月榜
     * @return
     */
    @Transactional
    @Override
    public String businessRiskListTopTen(String spage, String type, String year, String month) {
        //result
        Map<String, Object> result = Maps.newHashMap();
        //data
        List<RiskListTopTen> data = new ArrayList<>();
        //查询条件封装
        TopSearchCondition topCondition = new TopSearchCondition();
        //如果为空，默认为当前 年 月
        if(StringUtils.isBlank(year)){
            year = DateUtil.getYear();
        }
        topCondition.setYear(year);
        if(StringUtils.isBlank(month)){
            month = DateUtil.getMonth();
        }
        topCondition.setMonth(month);
        try {
            if (StringUtils.isBlank(spage)) {
                //没有查询页面
                throw new ConditionSPageException("Query condition(spage) is empty");
            } else {
                if (StringUtils.isBlank(type)) {
                    //没有查询类型
                    throw new ConditionTypeException("Query condition(type) is empty");
                } else if (ConstantStr.AREA_SPAGE.equals(spage) && ConstantStr.ORDER_BY_TIMES.equals(type)) {
                    //能够进行查询
                    // TODO: 2017/5/4 进行查询
                    List<RiskListTopTen> topTens;
                    List<PunishTop> punishTops;
                    //查询所有区域
                    topTens = businessRiskListTopTenMapper.selectAreaTopRanking();
                    if (topTens.size() > 0) {
                        for (RiskListTopTen p : topTens) {
                            if (null != p) {
                                RiskListTopTen riskListTopTen = new RiskListTopTen();
                                topCondition.setPosition(p.getTitle());
                                //根据处罚次数排序，返回当前区域下前10条数据
                                punishTops = businessRiskListTopTenMapper.selectAreaTopListByTime(topCondition);
                                if (punishTops.size() > 0) {
                                    riskListTopTen.setTitle(p.getTitle());
                                    riskListTopTen.setPunishtop(punishTops);
                                    data.add(riskListTopTen);
                                }
                            }
                        }
                        result.put(ConstantStr.DATA, data);
                        result.put(ConstantStr.CODE, CodeStateEnum.SUCCESS);
                    }
                } else if (ConstantStr.AREA_SPAGE.equals(spage) && ConstantStr.ORDER_BY_MONEY.equals(type)) {
                    List<RiskListTopTen> topTens;
                    List<PunishTop> punishTops;
                    //查询所有区域
                    topTens = businessRiskListTopTenMapper.selectAreaTopRanking();
                    if (topTens.size() > 0) {
                        for (RiskListTopTen p : topTens) {
                            if (null != p) {
                                RiskListTopTen riskListTopTen = new RiskListTopTen();
                                topCondition.setPosition(p.getTitle());
                                //根据处罚金额排序，返回当前区域下前10条数据
                                punishTops = businessRiskListTopTenMapper.selectAreaTopListByMoney(topCondition);
                                if (punishTops.size() > 0) {
                                    riskListTopTen.setTitle(p.getTitle());
                                    riskListTopTen.setPunishtop(punishTops);
                                    data.add(riskListTopTen);
                                }
                            }
                        }
                        result.put(ConstantStr.DATA, data);
                        result.put(ConstantStr.CODE, CodeStateEnum.SUCCESS);
                    }
                } else if (ConstantStr.INDUSTRY_SPAGE.equals(spage) && ConstantStr.ORDER_BY_TIMES.equals(type)) {
                    List<RiskListTopTen> topTens;
                    List<PunishTop> punishTops;
                    //查询所有行业，作为查询条件之一
                    topTens = businessRiskListTopTenMapper.selectIndustryTopRanking();
                    if (topTens.size() > 0) {
                        for (RiskListTopTen p : topTens) {
                            if (null != p) {
                                RiskListTopTen riskListTopTen = new RiskListTopTen();
                                topCondition.setIndustryType(p.getTitle());
                                //根据该行业处罚次数排序，返回当前行业下前10条数据
                                punishTops = businessRiskListTopTenMapper.selectIndustryTopListByTime(topCondition);
                                if (punishTops.size() > 0) {
                                    riskListTopTen.setTitle(p.getTitle());
                                    riskListTopTen.setPunishtop(punishTops);
                                    data.add(riskListTopTen);
                                }
                            }
                        }
                        result.put(ConstantStr.DATA, data);
                        result.put(ConstantStr.CODE, CodeStateEnum.SUCCESS);
                    }
                } else if (ConstantStr.INDUSTRY_SPAGE.equals(spage) && ConstantStr.ORDER_BY_MONEY.equals(type)) {
                    List<RiskListTopTen> topTens;
                    List<PunishTop> punishTops;
                    //返回行业总数
                    topTens = businessRiskListTopTenMapper.selectIndustryTopRanking();
                    if (topTens.size() > 0) {
                        for (RiskListTopTen p : topTens) {
                            if (null != p) {
                                RiskListTopTen riskListTopTen = new RiskListTopTen();
                                topCondition.setIndustryType(p.getTitle());
                                ////根据行业处罚金额排序，返回当前行业下前10条数据
                                punishTops = businessRiskListTopTenMapper.selectIndustryTopListByMoney(topCondition);
                                if (punishTops.size() > 0) {
                                    riskListTopTen.setTitle(p.getTitle());
                                    riskListTopTen.setPunishtop(punishTops);
                                    data.add(riskListTopTen);
                                }
                            }
                        }
                        result.put(ConstantStr.DATA, data);
                        result.put(ConstantStr.CODE, CodeStateEnum.SUCCESS);
                    }
                } else if (ConstantStr.AUTHORITY_SPAGE.equals(spage) && ConstantStr.ORDER_BY_TIMES.equals(type)) {
                    List<RiskListTopTen> topTens;
                    List<PunishTop> punishTops;
                    //查询所有行政单位，作为查询条件之一
                    topTens = businessRiskListTopTenMapper.selectAuthorityTopRanking();
                    if (topTens.size() > 0) {
                        for (RiskListTopTen p : topTens) {
                            if (null != p) {
                                RiskListTopTen riskListTopTen = new RiskListTopTen();
                                topCondition.setAuthority(p.getTitle());
                                ////根据行政单位处罚次数排序，返回前10条数据
                                punishTops = businessRiskListTopTenMapper.selectAuthorityTopListByTime(topCondition);
                                if (punishTops.size() > 0) {
                                    riskListTopTen.setTitle(p.getTitle());
                                    riskListTopTen.setPunishtop(punishTops);
                                    data.add(riskListTopTen);
                                }
                            }
                        }
                        result.put(ConstantStr.DATA, data);
                        result.put(ConstantStr.CODE, CodeStateEnum.SUCCESS);
                    }
                } else if (ConstantStr.AUTHORITY_SPAGE.equals(spage) && ConstantStr.ORDER_BY_MONEY.equals(type)) {
                    List<RiskListTopTen> topTens;
                    List<PunishTop> punishTops;
                    //查询所有的行政单位
                    topTens = businessRiskListTopTenMapper.selectAuthorityTopRanking();
                    if (topTens.size() > 0) {
                        for (RiskListTopTen p : topTens) {
                            if (null != p) {
                                RiskListTopTen riskListTopTen = new RiskListTopTen();
                                topCondition.setAuthority(p.getTitle());
                                ////根据处罚金额排序，返回当前区域下前10条数据
                                punishTops = businessRiskListTopTenMapper.selectAuthorityTopListByMoney(topCondition);
                                if (punishTops.size() > 0) {
                                    riskListTopTen.setTitle(p.getTitle());
                                    riskListTopTen.setPunishtop(punishTops);
                                    data.add(riskListTopTen);
                                }
                            }
                        }
                        result.put(ConstantStr.DATA, data);
                        result.put(ConstantStr.CODE, CodeStateEnum.SUCCESS);
                    }
                }
            }
        } catch (ConditionTypeException | ConditionSPageException e1) {
            throw e1;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result.put(ConstantStr.CODE, CodeStateEnum.FAIL);
            result.put(ConstantStr.MSG, e.getMessage());
            //所有的编译时异常，转化为运行时异常（运行时异常，spring可以做rollback的操作）
            throw new QueryException("Query inner error : " + e.getMessage());
        }
        return new Gson().toJson(result);
    }

    /**
     * 企业风险榜单-各地区、行业、行政 处罚菜单
     *
     * @param spage 1 地区  2 行业  3 行政
     * @return
     */
    @Transactional
    @Override
    public String businessRiskListMenu(String spage) {
        //result
        Map<String, Object> result = Maps.newHashMap();
        //data
        List<RiskMenu> data = new ArrayList<>();
        try {
            if (StringUtils.isBlank(spage)) {
                //没有查询类型
                throw new ConditionSPageException("Query condition(spage) is empty");
            } else {
                //能够进行查询
                // TODO: 2017/5/4 进行查询 注意格式
                if (ConstantStr.AREA_SPAGE.equals(spage)) {
                    //地理区域菜单
                    data = businessRiskListMenuMapper.selectAreaPunishMenu();
                } else if (ConstantStr.INDUSTRY_SPAGE.equals(spage)) {
                    //行业分类菜单及统计行业企业数量
                    data = businessRiskListMenuMapper.selectIndustryPunishMenu();
                } else if (ConstantStr.AUTHORITY_SPAGE.equals(spage)) {
                    //行政单位菜单及统计
                    data = businessRiskListMenuMapper.selectAuthorityPunishMenu();
                }
                result.put(ConstantStr.CODE, CodeStateEnum.SUCCESS);
            }
        } catch (ConditionSPageException e1) {
            throw e1;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result.put(ConstantStr.CODE, CodeStateEnum.FAIL);
            result.put(ConstantStr.MSG, e.getMessage());
            //所有的编译时异常，转化为运行时异常（运行时异常，spring可以做rollback的操作）
            throw new QueryException("Query inner error : " + e.getMessage());
        }
        result.put(ConstantStr.DATA, data);
        return new Gson().toJson(result);
    }

    /**
     * 企业风险榜单-各地区、行业、行政 处罚列表
     *
     * @param spage  当前页面（1 地理区域榜  2 行业分类榜  3 行政单位榜）
     * @param company 搜索关键字 （公司名称）
     * @param year 年榜
     * @param month 月榜
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @Transactional
    @Override
    public String businessRiskListView(String spage, Integer id,
                                       String company, String year, String month,
                                       Integer pageNumber, Integer pageSize) {
        //result
        Map<String, Object> result = Maps.newHashMap();
        //data
        List<RiskListView> data = Lists.newArrayList();

        TopSearchCondition businessCondition = new TopSearchCondition();
        //searchCondition
        //如果为空，默认为当前 年 月
        if(StringUtils.isBlank(year)){
            year = DateUtil.getYear();
        }
        businessCondition.setYear(year);
        if(StringUtils.isBlank(month)){
            month = DateUtil.getMonth();
        }
        businessCondition.setMonth(month);
        businessCondition.setPageNumber(pageNumber);
        businessCondition.setPageSize(pageSize);
        String pageNo = "";
        String totalPage = "";
        String totalRow = "";
        try {
            if (StringUtils.isBlank(company)) {
                //没有查询内容 -- 但是属于正常用户行为
                logger.warn("搜索关键词为空");
//                throw new ConditionTitleException("Query condition(company) is empty");
            }
            //可以查询
            businessCondition.setCompany(company);
            if (StringUtils.isBlank(spage)) {
                //没有查询类型
                throw new ConditionSPageException("Query condition(spage) is empty");
            } else {
                Page pageInfo = new Page();
                //能够进行查询
                if (ConstantStr.AREA_SPAGE.equals(spage)) {
                    //地理区域
                    businessCondition.setPosition(String.valueOf(id));
                    data = businessRiskListViewMapper.selectCompanyListByArea(businessCondition);
                    int rows = businessRiskListViewMapper.selectTotalRowOfArea(businessCondition);
                    pageInfo.setTotalRow(rows);
                } else if (ConstantStr.INDUSTRY_SPAGE.equals(spage)) {
                    //行业分类
                    businessCondition.setIndustryType(String.valueOf(id));
                    data = businessRiskListViewMapper.selectCompanyListByIndustry(businessCondition);
                    int rows = businessRiskListViewMapper.selectTotalRowOfIndustry(businessCondition);
                    pageInfo.setTotalRow(rows);
                } else if (ConstantStr.AUTHORITY_SPAGE.equals(spage)) {
                    //行政单位
                    businessCondition.setAuthority(String.valueOf(id));
                    data = businessRiskListViewMapper.selectCompanyListByAuthority(businessCondition);
                    int rows = businessRiskListViewMapper.selectTotalRowOfAuthority(businessCondition);
                    pageInfo.setTotalRow(rows);
                }
                pageInfo.setPageNumber(pageNumber);
                pageInfo.setPageSize(pageSize);
                result.put(ConstantStr.CODE, CodeStateEnum.SUCCESS);
                // TODO: 2017/5/4 赋值
                pageNo = String.valueOf(pageInfo.getPageNumber());
                totalPage = String.valueOf(pageInfo.getTotalPage());
                totalRow = String.valueOf(pageInfo.getTotalRow());
            }
        } catch (ConditionTypeException | ConditionTimeException e1) {
            throw e1;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result.put(ConstantStr.CODE, CodeStateEnum.FAIL);
            result.put(ConstantStr.MSG, e.getMessage());
            //所有的编译时异常，转化为运行时异常（运行时异常，spring可以做rollback的操作）
            throw new QueryException("Query inner error : " + e.getMessage());
        }
        result.put(ConstantStr.PAGESIZE, pageSize);
        result.put(ConstantStr.PAGE_NUMBER, pageNo);
        result.put(ConstantStr.TOTAL_PAGE, totalPage);
        result.put(ConstantStr.TOTAL_ROW, totalRow);
        result.put(ConstantStr.DATA, data);
        return new Gson().toJson(result);
    }
}
